﻿CREATE PROCEDURE [dbo].[Articles_InsertFromTempInventories]
	@RangeReviewId int
AS

declare @startDate DATE = (select FirstMonth from RangeReviews where Id = @RangeReviewId)
declare @totalMonths INT = (select TotalMonths from RangeReviews where Id = @RangeReviewId)
declare @startDatePY DATE = 
	(
		select CASE WHEN HasPriorYear = 1 THEN DATEADD(Month, -12, FirstMonth) ELSE FirstMonth END
		from RangeReviews where Id = @RangeReviewId
	)
declare @endDate DATE = DATEADD(Month, @totalMonths - 1, @startDate)

INSERT INTO Articles(RangeReviewId, CategoryId, Code, Name, EAN, Brand, Manufacturer, Delist, IsDelisted, IsDeletedRangeReview, IsDeletedPerformance, IsNew, TaxRate, Source)
SELECT @RangeReviewId RangeReviewId, CategoryId, ArticleCode, MAX(Description), MAX(EAN), MAX(Brand), MAX(Manufacturer), 0, 1, 1, 0, 0, 0, 'InventoriesMaster'
FROM TempInventories
WHERE ArticleId = 0 and Cost > 0
AND ((Date BETWEEN @startDatePY AND DATEADD(Month, @totalMonths - 1, @startDatePY)) OR (Date Between @startDate AND @endDate))
GROUP BY ArticleCode, CategoryId

--Hago Update del ArticleId en Inventories
Update TempInventories
Set ArticleId = a.Id
From TempInventories t
Inner Join Articles a on t.ArticleCode = a.Code and a.UOM is null and t.ArticleId = 0

